package net.csdn.business.common.exception;

import lombok.Getter;
import net.csdn.business.common.enums.ResultCodeEnum;
import net.csdn.business.common.i18n.LocaleMessageUtil;
import org.apache.commons.lang3.ArrayUtils;

import java.util.Objects;

/**
 * @author likun
 * @date 2022/5/6 15:38
 */
@Getter
public class BusinessException extends RuntimeException {
    private final int code;
    private final String msg;

    /**
     * {@link ResultCodeEnum#name()}
     */
    private final String resultCodeName;

    public BusinessException(int code, String msg) {
        super(msg);
        this.code = code;
        this.msg = msg;
        this.resultCodeName = "UN_KNOW";
    }

    public BusinessException(int code, String msg, String resultCodeName) {
        super(msg);
        this.code = code;
        this.msg = msg;
        this.resultCodeName = resultCodeName;
    }

    public BusinessException(int code, String msg, String resultCodeName, Throwable cause) {
        super(msg, cause);
        this.code = code;
        this.msg = msg;
        this.resultCodeName = resultCodeName;
    }

    public BusinessException(ResultCodeEnum codeEnum) {
        super(codeEnum.getMsg());
        this.code = codeEnum.getCode();
        this.msg = LocaleMessageUtil.getMessage(codeEnum);
        this.resultCodeName = codeEnum.name();
    }

    public BusinessException(ResultCodeEnum codeEnum, String regMsg) {
        super(codeEnum.getMsg());
        this.code = codeEnum.getCode();
        String errMsg = LocaleMessageUtil.getMessage(codeEnum);
        regMsg = Objects.toString(regMsg, "");
        this.msg = String.format(errMsg, regMsg);
        this.resultCodeName = codeEnum.name();
    }

    public BusinessException(ResultCodeEnum codeEnum, String msg, Object... regMsg) {
        super(msg);
        this.code = codeEnum.getCode();
        if (ArrayUtils.isEmpty(regMsg)) {
            this.msg = msg;
        } else {
            this.msg = String.format(msg, regMsg);
        }
        this.resultCodeName = codeEnum.name();
    }

    public BusinessException(ResultCodeEnum codeEnum, Throwable cause) {
        super(codeEnum.getMsg(), cause);
        this.code = codeEnum.getCode();
        this.msg = LocaleMessageUtil.getMessage(codeEnum);
        this.resultCodeName = codeEnum.name();
    }
}